<template>
  <div class="layout">
    <h2 class="function-header">咨询反馈</h2>
    <div class="feedback-container">
      <div class="left-list">
        <div class="subject-item" v-for="item in tableData" :key="item.id" :class="{ active: theItem.id == item.id }" @click="changeItem(item)">
          <el-tag type="primary" v-if="item.status == 'OPEN'">待处理</el-tag>
          <el-tag type="success" v-if="item.status == 'PROCESSING'">处理中</el-tag>
          <el-tag type="info" v-if="item.status == 'CLOSED'">已结束</el-tag>
          <p class="name">{{item.subject}}</p>
          <span class="unReadCount" v-if="item.userUnreadCount > 0">{{item.userUnreadCount}}</span>
        </div>
        <el-pagination  
          v-if="tableData && tableData.length > 0"
          style="justify-content: center;margin-top: 10px;" 
          layout="prev, pager, next" 
          :page-sizes="[10,15,30,50]"  
          :pager-count="4" 
          :total="queryData.total" 
          @currentChange="handleCurrentChange" 
          @changeSize="handleSizeChange"
        />
      </div>
      <div class="right-content">
        <div class="top-but">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="咨询" name="consultation"></el-tab-pane>
            <el-tab-pane label="反馈内容" name="feedback" v-if="theItem"></el-tab-pane>
          </el-tabs>
          <div class="right-but">
            <el-button type="primary" @click="addFeedback">新增反馈</el-button>
          </div>
        </div>
        <div class="bottom-box">
          <!-- 回复对话  -->
          <div class="comment-box" v-if="activeName == 'consultation'">
            <el-scrollbar ref="scrollbarRef" height="500px" style="padding-right: 20px;padding-top: 20px;">
              <div class="comment-list" ref="commentListRef">
                <!-- 管理员回复 -->
                <div class="comment-item" v-for="item in commentList" :key="item.id" :class="[item.userSending ? 'self' : 'other']">
                  <span class="time">{{ formatDate(item.createdAt) }}</span>
                  <div class="bubble" :class="[item.userSending ? 'self' : 'other']">
                    <p>{{ item.content }}</p>
                  </div>
                </div>
                <div v-if="!(tableData && tableData.length > 0)">
                  <p class="empty-tip">您还没有提问，请点击右上角“新增反馈”进行提问</p>
                </div>
                <div v-else-if="!(commentList && commentList.length > 0)">
                  <p class="empty-tip">回复正在处理中，您可以通过留言与我们进一步沟通</p>
                </div>
              </div>
            </el-scrollbar>
            <div class="comment-bottom" style="padding-right: 20px;">
              <el-input v-model="theContent" placeholder="请输入内容" type="textarea" rows="2" maxlength="500" :disabled="theItem?.status == 'CLOSED'"/>
              <div class="button-list">
                <el-button type="" @click="endFeedback" :disabled="theItem?.status == 'CLOSED'">结束咨询</el-button>
                <el-button @click="addComment" type="primary" style="float: right;" :disabled="theItem?.status == 'CLOSED'">发送</el-button>
              </div>
            </div>
           
          </div>
          <!-- 已填写反馈 -->
          <div class="form-box" v-else>
            <FormEcho :formData="answerDetail" :modelValue="answerForm" height="350px" :disabled="true" :showDevice="false" :simple="true" :boxShadow="false"/>
            <!-- <FormEcho :formData="answerDetail"  height="510px" :disabled="true" :showDevice="false" :simple="true" :boxShadow="false"/> -->
          </div>
        </div>
      </div>
    </div>
    <el-dialog v-model="showFeedback" title="问题反馈" width="600px">
      <FormEcho v-if="preViewFormInfo" :formData="preViewFormInfo" ref="childRef" height="510px" :disabled="false" :showDevice="false" :simple="true" :boxShadow="false"/>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="showFeedback = false">取消</el-button>
          <el-button type="primary" @click="insertFeedback" class="sub-button">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { 
  Createfeedback,
  userPagingFeedback,
  getThreadDetailFeedback,
  userReplyFeedback,
  closeFeedback
 } from '@/api/feedback'
import { FormEcho } from "@ruifox-cms/components";
import { selectPaper, getAnswerDetail } from '@/api/form'
import { formatDate } from '@/utils/tools'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pagingConfig } from '@/api/setting'
import { tableList as mixTable } from "@ruifox-cms/utils";

const getListFunc = async () => {
  console.log("tableData", tableData.value);
  theItem.value = tableData.value[0] || {};
  console.log("theItem.value", theItem.value);
  await getComment()
  
}
//左侧反馈列表分页器
const { queryData, tableData, getTableData } = mixTable({
  getListApi: userPagingFeedback,
  getListFunc
})


const defaultQuery = {
  currentPage: 1,
  pageSize: 10,
  formId: "",
  userId: "",
  headId: "",
  status: "",
  unreadForAdmin: false,
  unreadForUser: false
}
Object.assign(queryData, defaultQuery);

const handleCurrentChange = (page) => {
  queryData.currentPage = page;
  getTableData();
}
const handleSizeChange = (size) => {
  // 返回size
  console.log("handleSizeChange", size);
}

const preViewFormInfo = ref()
const preViewFormInfoLoading = ref(false)

const getForm = async () => {
  preViewFormInfoLoading.value = true
  let res = await selectPaper({ formId: formId.value })
  preViewFormInfo.value = res.data
  // store.commit('formDesignInfo/SET_FORMINFO', res.data)
  preViewFormInfoLoading.value = false
}
const formId = ref()
//获取基本设置信息
const system = ref({
  "currentPage": 1,
  "pageSize": 10,
  "name": "",
  "using": true,
})
const getInfo = async () => {
  const res = await pagingConfig(system.value)
  if(res.code == 20000){
    formId.value = res.data.list[0].config.feedbackFormTemplateId
  }
}
const defaultForm = reactive({
  formId: "",
  subject: ""
})
const feedbackForm = ref({...defaultForm})
//获取表单提交的数据
const childRef = ref(null);
const insertFeedback = async () => {
  if (childRef.value) {
    try {
      const result = await childRef.value.submit(formId.value, 0);
      const getValue = childRef.value.getValue()
      const firstValue = Object.values(getValue)[0];
      feedbackForm.value.formId = result
      feedbackForm.value.subject = firstValue
      //如果在表单系统那边提交成功 提交结果返回
      if (result) {
        const res = await Createfeedback(feedbackForm.value)
        if(res.code == 20000){
          console.log("成功");
          ElMessage.success("提交成功");
          getTableData();
          getForm();
          showFeedback.value = false
        }
      }
    } catch (error) {
      console.error('调用子组件 submit 方法出错:', error);
    }
  }
};

//获取已填写反馈
const answerDetail = ref()
const answerForm = ref({})
const getFormResult = async () => {
  console.log("theItem.value.formId",theItem.value.formId);

  let res = await getAnswerDetail({ id: theItem.value.formId, formId: formId.value })
  if (res.code == 20000) {
    answerDetail.value = res.data;
    res.data.formItemList.forEach(item => {
      answerForm.value[item.formItemId] = item.modelValue
    })
  }
}

const theItem = ref() //默认第一个为激活主题
const changeItem = (item) => {
  theItem.value = item;
  getComment();
  getFormResult();
}

//获取对话内容
const commentList = ref([])
const getComment = async () => {
  console.log("获取第一个反馈",theItem.value);
  
  const res = await getThreadDetailFeedback({ threadId: theItem.value.id })
  if(res.code == 20000){
    commentList.value = res.data.feedbackMessages
    // console.log("commentList",commentList.value);
  }
}

//切换显示
const activeName = ref('consultation')
const scrollbarRef = ref(null)
const commentListRef = ref(null)
const theContent = ref('')
const addComment = async () => {
  if(theContent.value.trim() == ''){
    ElMessage.warning('内容不能为空')
    return
  }
  const res = await userReplyFeedback({threadId: theItem.value.id, content: theContent.value})
  if(res.code == 20000){
    await getComment();
    theContent.value = '';
    await nextTick();
    await scrollToBottom();
    getTableData()
  }

}
const scrollToBottom = () => {
  if (scrollbarRef.value) {
    const scrollContainer = scrollbarRef.value.$el.querySelector(".el-scrollbar__wrap");
    if (scrollContainer) {
      scrollContainer.scrollTo({
        top: scrollContainer.scrollHeight + 1000,
        behavior: "smooth", 
      });
    }
  } else if (commentListRef.value) {
    // 备用方案：直接操作DOM
    commentListRef.value.scrollTop = commentListRef.value.scrollHeight;
  }
}
const showFeedback = ref(false)
const addFeedback = () => {
  showFeedback.value = true
}
const endFeedback = async () => {
  ElMessageBox.confirm('结束后将不能继续咨询，如还有其他问题请点击新增反馈', '确认结束咨询', {
    distinguishCancelAndClose: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    const res = await closeFeedback({threadId: theItem.value.id})
    if(res.code == 20000){
      ElMessage.success("已结束本次咨询")
      // clearInterval(timer) //结束后关闭定时器
    }
  })
}

let timer = null
onMounted(async() => {
  // 表单
  await getInfo()
  await getForm();
  await getTableData();
  await getComment()
  // timer = setInterval(getComment, 3000)
  timer = setInterval(() => {
    getComment();
    getTableData();
  },3000)
});
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped lang="scss">
.function-header{
  margin-top: px2rem(40);
  font-weight: normal;
  font-size: px2rem(24);
}
.feedback-container{
  display: flex;
  margin-top: px2rem(40);
  .left-list{
    width: px2rem(300);
    border-right: 1px solid #eee;
    overflow-y: auto;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0,0,0,0.05);
    border: 1px solid $borderColor;
    border-radius: 5px;
    min-height: calc(500px + 1.9rem);
    .subject-item{
      padding: px2rem(12) px2rem(16);
      /* margin-bottom: px2rem(10); */
      cursor: pointer;
      position: relative;
      display: flex;
      align-items: center;
      border-bottom: 1px solid $borderColor;
      &:hover,&.active {
        background-color: #f9f9f9;
        border-radius: px2rem(5);
        /* color: $mainColorColor; */
      }
      .unReadCount{
        position: absolute;
        right: px2rem(16);
        top: 50%;
        transform: translateY(-50%);
        height: px2rem(25);
        width: px2rem(25);
        border-radius: 50%;
        background: rgba($partyColor,.6);
        color: white;
        font-size: px2rem(16);
        text-align: center;
        line-height: px2rem(25);
      }
      p{
        margin-left: px2rem(10);
        font-size: px2rem(14);
        @include textEllipsis(21,1)
      }
    }
  }
  .right-content{
    margin-left: px2rem(20);
    flex: 1;
    .top-but{
      display: flex;
      justify-content: space-between;
      .demo-tabs{
        margin-bottom: 0;
      }
      .right-but{
        display: flex;
      }
    }
    .bottom-box{
      padding: 0 px2rem(20) px2rem(40) px2rem(40);
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
      border: 1px solid $borderColor;
      .sub-button{
        margin-left: 72px;
      }
      .comment-box{
        .comment-list {
          /* max-width: 600px; */
          margin: 0 auto;
          .comment-item{
            display: flex;
            flex-direction: column;
            align-items: end;
            margin-bottom: px2rem(10);
            &.other{
              align-items: start;
            }
            .time {
              display: block;
              font-size: px2rem(14);
              color: #666;
              margin-bottom: 0;
            }
          }
          .bubble {
            max-width: 70%;
            padding: px2rem(10) px2rem(12);
            border-radius: px2rem(10);
            margin: px2rem(6) 0 px2rem(8);
            position: relative;
            color: $black;
            &.self {
              background: #c9e7ff;
              border-bottom-right-radius: 4px;
            }
            &.other{
              background: #e4e5e7;
            }
          }
        }
      }
    }
  }
  .button-list{
    margin-top: px2rem(20);
    display: flex;
    justify-content: space-between;
  }
}
.empty-tip{
  font-size: px2rem(24);
  color: #ccc;
  text-align: center;
  margin-top: px2rem(100);
}
</style>